<?php
/**
 * Created by PhpStorm.
 * User: 10838
 * Date: 2017/11/3
 * Time: 10:12
 */
namespace app\index\controller;

use app\index\model\UserModel;
use mg_api\Mg_api;
use think\Controller;
use think\Db;
use think\Loader;
use think\Validate;
use wechat\wechatCallbackapiTest;

include EXTEND_PATH . 'code/Code.php';

class Login extends Controller
{
    public function _initialize()
    {
        Loader::import('mg_api.Mg_api');
       /* Loader::import('wechat.wechatCallbackapiTest');*/
      /*  $wechat = new wechatCallbackapiTest();
        $data = $wechat->get_openid($_GET['code']);
        $_SESSION['openid'] = $data['openid'];*/
    }


    public static function firstTest(){

        Db::table('dx_logo')->insert([
            'title'=>'ewwe',
            'description'=>date("Y-m-d H:i:s")
        ]);



    }


    public function login()
    {
        return view('login');
    }

    //登录验证码
    public function code()
    {
        header("Content-type: text/html; charset=utf-8");
        date_default_timezone_set('PRC'); //设置默认时区为北京时间
        $code = new \code\Code();
        //验证码
        $code_num = rand(1000, 9999);
       $code->telphone = $_SESSION['tel'];
        $_SESSION['code'] = $code_num;
        $re = $code->send($code_num);
      if ($re) {
            return view('code');
        } else {
            $this->error('验证码发送失败');
        }
    }

    //查询能否用opneid查询到数据
    public function is_openid($openid)
    {
        $mg_api = new Mg_api();
        $data = [
            //获取积分
            'key' => 'Get_LinkMan',
            'wx_openid' => $openid
        ];
        $is_openid = $mg_api->api($data);
        $is_openid = json_decode($is_openid, true);
        return $is_openid;
    }

    //查询手机号
    public function is_tel($tel)
    {
        $mg_api = new Mg_api();
        $data = [
            'key' => 'isTrue',
            'F_Tel' => $tel,
        ];
        $tel = $mg_api->api($data);
        $tel = json_decode($tel, true);
        //var_dump($tel);
        return $tel;
    }

    public function get_code1()
    {
        if($_POST['tel']){
            $_SESSION['tel']=$_POST['tel'];
            if (!isset($_SESSION['openid'])) {
                echo '请用微信打开';
                return;
            }
            //1.先验证此微信号openid能否获取数据
            $is_openid = $this->is_openid($_SESSION['openid']);
            //1。查询手机号
            $is_tel = $this->is_tel($_POST['tel']);
            if($is_openid['Status']){
                //在接口中能用次openid 查找到数据
                //接收查询到的号码并分解
                $tel = explode('/', $is_openid['JData']['0']['f_tel']);
                if(in_array($_POST['tel'],$tel)){
                    //如果登录的号码在查询到的号码中
                    //c查询此微信号是否在本地数据库中
                    $user = UserModel::where('openid',$_SESSION['openid'])->find();
                    if($user){
                        //两个都为真更新数据库
                        $re = UserModel::where('openid',$_SESSION['openid'])->update([
                            'user_name' => $is_openid['JData'][0]['f_name'],
                            'user_tel' =>$is_openid['JData'][0]['f_tel'],
                            'user_sex'=>$is_openid['JData'][0]['sex'] == '男'?1:0,
                            'position'=>$is_openid['JData'][0]['f_gw'],
                            'companyname'=>$is_openid['JData'][0]['f_companyname'],
                            'company_id'=>$is_openid['JData'][0]['f_intermediaryid'],
                            'is_pass'=>1
                        ]);
                        $user = UserModel::where('openid',$_SESSION['openid'])->find();

                        //查询到
                        if($user->is_pass == 0){
                            echo '此账号未通过审核,请联系工作人员';
                            return;
                        }else {
                            //登录下一步
                            echo 1;//1可以登录
                            return;
                        }
                    }else{
                        //本地没有
                        //下一步
                        echo 2;//2本地没有此数据但是接口中有此openid
                        return;
                    }
                    return;
                }else{
                    echo '该微信没有绑定此手机号';
                    return;
                }
            }else{
			
                $user = UserModel::where('openid',$_SESSION['openid'])
                    ->find();
               //
                if($user){
                    $tel = explode('/', $user->user_tel);
                    if($user->user_tel){
                        if(in_array($_POST['tel'],$tel)){
                            //此情情况  值存在于 用户  注册后 没有通过审核
                            if($user->is_pass == 0){
                                echo '此账号未通过审核';
                                return;
                            }
                        }else{
                            echo '该微信号于此手机号不匹配';
                            return;
                        }
                    }else{
                        echo 3;
                        return;
                    }
                }else{
                    if(!$is_tel){
                        echo '请注册!';
                        return;
                    }
                    //没有用微信号获取到用户的资料
                    if($is_tel['Message'] == '该电话号码存在。'){
                        //如果此电话在api中存在
                        echo 3;//下一步 3接口中有此号码需要下一步绑定
                        return;

                    }elseif($is_tel['Message'] == '该电话号码不存在，请注册。'){
                        echo "该电话号码不存在，请注册。";
                        return;
                    } else{
                        echo '参数错误';
                        return;
                    }
                }
            }
        }
    }

    //验证码比较
    public function verify()
    {
        $code = implode('', $_POST['code']);
        if ($code == $_SESSION['code']) {

            //存在  传递信息
            //获取openid
            if ($_SESSION['openid'] == "") {
                $this->error("没有openid");
            }
            $mg_api = new Mg_api();
            $api_data = [
                //档案绑定
                'key' => "bind_LinkMan",
                'F_Tel' => $_SESSION['tel'],
                'wx_openid' => $_SESSION['openid']
            ];
            $bangding = $mg_api->api($api_data);
            $bangding = json_decode($bangding, true);

            if ($bangding['Status']) {

                //绑定成功
                //拉取用户的信息
                $re = $this->getuser_data($_SESSION['openid'], $_SESSION['tel']);


                if ($re) {
                    //写入本数据成功
                    //跳转到index

                    return redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7f82feeff1f94fb&redirect_uri=http%3a%2f%2fssq.shushimall.com&response_type=code&scope=snsapi_userinfo&state=diyadaikuan#wechat_redirect");
                } else {
                    //拉取用户信息写入失败

                    $this->error('拉取用户信息写入失败');
                }
            } else {
                //绑定失败

                $this->error('档案绑定失败');
            }


        } else {
            $this->error('验证码输入错误');
        }
    }

    //退出
    public function login_out()
    {
        $_SESSION['user_id'] = "";
        $this->redirect('index/index/index');
    }

    //注册
    public function zhuce()
    {
        $mg_api = new Mg_api();
        $api_data = [
            'key' => "Get_hbgw"
        ];
        $position = $mg_api->api($api_data);
        $position = json_decode($position, true);
        $position = $position['JData'];

        $this->assign('position', $position);
        return view('zhuce');
    }

    //注册表单
    public function zhuce_from()
    {
        if(!isset($_SESSION['zhuce_code'])){
            $this->error('没有获取到验证码');
        }

        //判断验证码
        if ($_POST['code'] == $_SESSION['zhuce_code']) {
            $data = [
                'user_name' => $_POST['name'],
                'user_sex' => $_POST['sex'],
                'company' => $_POST['company'],
                'position' => $_POST['position'],
                'user_tel' => $_POST['tel'],
                'openid' => $_SESSION['openid'],
                'time' => time(),
                'is_pass' => 0,
                'referee' => $_POST['referee']
            ];
            $validate = $this->zhuce_validate();
            $result = $validate->check($data);
            //查询是否存在openid

            if ($result) {
                $count = UserModel::where('openid',$_SESSION['openid'])->count();
                if($count){
                    $re = UserModel::where('openid',$_SESSION['openid'])->update($data);
                }else{
                    $re = UserModel::create($data);
                }
                if ($re) {
                    $this->success('注册成功请等待审核', Url("index/login/login"));
                } else {
                    $this->error('注册失败，稍后重试');
                }

            } else {
                $this->error($validate->getError());
            }
        } else {
            $this->error('验证码错误');
        }
    }

    //注册验证码
    public function zhuce_code()
    {
        $re = UserModel::where('user_tel', $_POST['tel'])->find();

        if ($re) {
            echo 1;//此手机已注册
        } else {
            //调用接口查询此号码是否存在
            $mg_api = new Mg_api();
            $api_data = [
                'key' => "isTrue",
                'F_Tel' => $_POST['tel']

            ];
            $mg_api_tel = $mg_api->api($api_data);
            $mg_api_tel = json_decode($mg_api_tel, true);
            $mg_api_tel = $mg_api_tel['Message'];
            if ($mg_api_tel == '该电话号码存在。') {
                echo 1;
                return;
            }

            header("Content-type: text/html; charset=utf-8");
            $code = new \code\Code();
            //验证码
            $code_num = rand(1000, 9999);
            $code->telphone = $_POST['tel'];
            $_SESSION['zhuce_code'] = $code_num;
            $re_code = $code->send($code_num);
            if ($re_code) {
                echo 2;//验证码发生成功；

            } else {
                echo 3;//验证码发送失败;
            }
        }
    }

    //注册表单验证
    public function zhuce_validate()
    {
        $yanzheng = [
            'user_name' => 'require',
            'user_tel' => 'number|length:11',
            'company' => 'require',
        ];
        $msg = [
            'user_name.require' => '昵称名不能为空',
            'user_tel.number' => '电话必须为数字',
            'user_tel.length' => '电话必须为11数',
            'company.require' => '所在公司不能为空',
        ];
        $validate = new Validate($yanzheng, $msg);
        return $validate;
    }

    //拉取用户信息并写入本地数据
    public function getuser_data($openid)
    {
        $mg_api = new Mg_api();
        $api_data = [
            'key' => "Get_LinkMan",
            'wx_openid' => $openid
        ];
        $data = $mg_api->api($api_data);
        $data = json_decode($data, true);


        if ($data['JData']['0']['sex'] == "男") {
            $sex = '1';
        } elseif ($data['JData']['0']['sex'] == "女") {
            $sex = "0";
        }
        $user_new = [
            'user_name' => $data['JData']['0']['f_name'],
            'user_tel' => $data['JData']['0']['f_tel'],
            'user_sex' => $sex,
            'position' => $data['JData']['0']['f_gw'],
            'openid' => $openid,
            'is_pass' => '1',
         //  'time' => time(),
            'company_id' => $data['JData']['0']['f_intermediaryid'],
            'company' => $data['JData']['0']['f_companyname'],
            'companyname' => $data['JData']['0']['f_companyname'],

        ];
		//查询是否存在openid
		$re = UserModel::where('openid',$openid)->find();
		if($re){
			UserModel::where('openid',$openid)->update($user_new);
		}else{
			UserModel::create($user_new);
		}
       
        return $user_new;


    }

}
